package com.teemor.im.remoting.instance;

import com.teemor.im.common.exception.ImException;
import com.teemor.im.discovery.node.ServerNode;
import com.teemor.im.remoting.netty.CommandDispatcherHandler;
import com.teemor.im.remoting.netty.NettyClientConfig;
import com.teemor.im.remoting.netty.RmtMessageDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ename zhoulk
 * @cname 周李科
 * @date 2020/6/16 13:46
 */
@Slf4j
public class NettyRemotingClient extends NettyRemotingAbstract implements RemotingService {

    private final Lock lockChannelTables = new ReentrantLock();
    private static final long LOCK_TIMEOUT_MILLIS = 3000;
    private final Bootstrap bootstrap;
    private final EventLoopGroup eventLoopGroupWorker;
    private DefaultEventExecutorGroup defaultEventExecutorGroup;
    private final NettyClientConfig nettyClientConfig = new NettyClientConfig();
    /**
     * 缓存连接对象
     */
    private final Map<ServerNode, ConnectWrapper> connectMap = new ConcurrentHashMap<>();


    private static volatile NettyRemotingClient instance;


    static final int permitsOneway = 65536;
    static final int permitsAsync = 65536;

    public static NettyRemotingClient instance() {
        if (instance == null) {
            synchronized (NettyRemotingClient.class) {
                if (instance == null) {
                    instance = new NettyRemotingClient();
                }
            }
        }
        return instance;
    }

    public NettyRemotingClient() {
        super(permitsOneway, permitsAsync);
        this.eventLoopGroupWorker = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap();
    }


    @Override
    public boolean isActive() {
        return true;
    }

    @Override
    public void start() {
        this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(
                nettyClientConfig.getClientWorkerThreads(),
                new ThreadFactory() {
                    private AtomicInteger threadIndex = new AtomicInteger(0);

                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet());
                    }
                });
        this.bootstrap.group(this.eventLoopGroupWorker)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringEncoder());
//                        pipeline.addLast(new LineBasedFrameDecoder(1024 * 1024));
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new RmtMessageDecoder());

                        //命令分发handler
                        pipeline.addLast(new CommandDispatcherHandler(NettyRemotingClient.super.responseMap));
                    }
                });
    }

    @Override
    public void stop() {
        this.eventLoopGroupWorker.shutdownGracefully();
    }

    @Override
    public void restart() {

    }

    public static SocketAddress getSocketAddress(ServerNode node) {
        return new InetSocketAddress(node.getHost(), node.getPort());
    }

    @Override
    public ExecutorService callbackExecutor() {
        return null;
    }

    @Override
    protected Channel channel(ServerNode node) {
        return this.getAndCreateChannel(node);
    }

    private Channel getAndCreateChannel(final ServerNode node) {
        if (null == node) {
            throw new ImException("");
        }

        ConnectWrapper cw = this.connectMap.get(node);
        if (cw != null && cw.isOK()) {
            return cw.getChannel();
        }

        return this.connect(node);
    }

    public Channel connect(ServerNode node){
        ConnectWrapper cw = this.connectMap.get(node);
        if (cw != null && cw.isOK()) {
            return cw.getChannel();
        }
        try {
            if (this.lockChannelTables.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
                try {
                    boolean createNewConnection;
                    cw = this.connectMap.get(node);
                    if (cw != null) {
                        if (cw.isOK()) {
                            return cw.getChannel();
                        } else if (!cw.getChannelFuture().isDone()) {
                            createNewConnection = false;
                        } else {
                            this.connectMap.remove(node);
                            createNewConnection = true;
                        }
                    } else {
                        createNewConnection = true;
                    }

                    if (createNewConnection) {
                        ChannelFuture channelFuture = this.bootstrap.connect(getSocketAddress(node));
                        channelFuture.addListener(future -> {
                            EventLoop eventLoop = channelFuture.channel().eventLoop();
                            if (!future.isSuccess()) {
                                log.info("连接失败!在5s之后准备尝试重连!");
                                eventLoop.schedule(() -> {
                                    try {
                                        NettyRemotingClient.this.connect(node);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }, 5, TimeUnit.SECONDS);
                            } else {
                                log.info("connect node {} success", node.toString());
                            }
                        });
                        log.info("createChannel: begin to connect remotingService host[{}] asynchronously", node);
                        cw = new ConnectWrapper(channelFuture);
                        this.connectMap.put(node, cw);
                        node.setRemotingService(this);
                    }
                } catch (Exception e) {
                    log.error("createChannel: create channel exception", e);
                } finally {
                    this.lockChannelTables.unlock();
                }
            } else {
                log.warn("createChannel: try to lock channel table, but timeout, {}ms", LOCK_TIMEOUT_MILLIS);
            }
        } catch (InterruptedException e) {
            log.info("connect node {} failed", node.toString());
        }

        if (cw != null) {
            ChannelFuture channelFuture = cw.getChannelFuture();
            if (channelFuture.awaitUninterruptibly(this.nettyClientConfig.getConnectTimeoutMillis())) {
                if (cw.isOK()) {
                    log.info("createChannel: connect remotingService host[{}] success, {}", node, channelFuture.toString());
                    return cw.getChannel();
                } else {
                    log.warn("createChannel: connect remotingService host[" + node + "] failed, " + channelFuture.toString(), channelFuture.cause());
                }
            } else {
                log.warn("createChannel: connect remotingService host[{}] timeout {}ms, {}", node, this.nettyClientConfig.getConnectTimeoutMillis(),
                        channelFuture.toString());
            }
        }
        return null;
    }


    public static class ConnectWrapper {
        private final ChannelFuture channelFuture;

        public ConnectWrapper(ChannelFuture channelFuture) {
            this.channelFuture = channelFuture;
        }

        public boolean isOK() {
            return this.channelFuture.channel() != null && this.channelFuture.channel().isActive();
        }

        public boolean isWritable() {
            return this.channelFuture.channel().isWritable();
        }

        public Channel getChannel() {
            return this.channelFuture.channel();
        }

        public ChannelFuture getChannelFuture() {
            return channelFuture;
        }
    }
}


